package cn.liwq.demo.web.util;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * <p>Project: demo-common </p>
 * <p>Function:  </p>
 * <p>Description:  </p>
 * <p>Copyright: Copyright(c) 2018 Ucarinc </p>
 * <p>Company: Ucarinc </p>
 *
 * @author weiqiang.li@ucarinc.com
 * @version 1.0
 * @date 2018-08-16 11:23:11
 */
public class ClassScanner {

    private static ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    private final static String FILE_PROTOCOL = "file";

    private final static String JAR_PROTOCOL = "jar";

    private final static String CLASS_SUFFIX = ".class";

    public static List<Class<?>> loadClass(String pacakgeName, Class<?>... filter) {
        URL url = classLoader.getResource(toggleDotSlash(pacakgeName));
        String protocol = url.getProtocol();
        if (FILE_PROTOCOL.equals(protocol)) {
            return loadClassFromFile(pacakgeName, filter);
        } else if (JAR_PROTOCOL.equals(protocol)) {
            return loadClassFromJar(pacakgeName, filter);
        }
        return null;
    }

    private static List<Class<?>> loadClassFromFile(String pacakgeName, Class[] filter) {
        List<Class<?>> classList = new ArrayList<>();
        URI uri = null;
        try {
            uri = classLoader.getResource(toggleDotSlash(pacakgeName)).toURI();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        File file = new File(uri);
        file.listFiles(f -> {
            if (f.isDirectory()) {
                loadClassFromFile(pacakgeName + "." + f.getName(), filter);
            } else if (f.getName().endsWith(CLASS_SUFFIX)) {
                Class<?> clazz = null;
                try {
                    clazz = classLoader.loadClass(pacakgeName + "." + removeClassExt(f.getName()));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                if (!isFiltered(clazz, filter)) {
                    classList.add(clazz);
                }

                return true;
            }
            return false;
        });
        return classList;
    }

    private static List<Class<?>> loadClassFromJar(String pacakgeName, Class[] filter) {
        List<Class<?>> classList = new ArrayList<>();
        String pathName = toggleDotSlash(pacakgeName);
        JarFile jarFile = null;
        URL url = classLoader.getResource(pathName);
        try {
            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
            jarFile = jarURLConnection.getJarFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration<JarEntry> jarEntries = jarFile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            if (jarEntryName.contains(pathName) && !jarEntryName.equals(pathName + "/")) {
                if (jarEntry.isDirectory()) {
                    String className = toggleDotSlash(jarEntryName.substring(0, jarEntryName.length() - 1));
                    loadClassFromJar(className, filter);
                } else if (jarEntryName.endsWith(CLASS_SUFFIX)) {
                    Class<?> clazz = null;
                    try {
                        clazz = classLoader.loadClass(toggleDotSlash(removeClassExt(jarEntryName)));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (!isFiltered(clazz, filter)) {
                        classList.add(clazz);
                    }
                }
            }
        }
        return classList;
    }

    private static boolean isFiltered(Class<?> clazz, Class[] filerClassArr) {
        if (filerClassArr.length == 0) {
            return false;
        }
        for (Class filterClass : filerClassArr) {
//            if (filterClass.isAssignableFrom(clazz)) {
//                return false;
//            }
            if (clazz.isAnnotationPresent(filterClass)) {
                return false;
            }
        }
        return true;
    }

    private static String toggleDotSlash(String str) {
        return str.contains(".") ? str.replaceAll("\\.", "/") : str.replaceAll("/", ".");
    }

    private static String removeClassExt(String pathName) {
        int pos = pathName.lastIndexOf(".");
        return pathName.substring(0, pos);
    }

    public static void main(String[] args) {
//        classScanner.loadClass("cn.liwq.demo.java", Note.class);
//        classScanner.loadClass("net.sf.cglib");
    }
}
